using System.Collections;
using System.Text;

public class TypeContext
{
    private readonly GlobalContext _global;

    private readonly TypeDefinition _type;
    private readonly Dictionary<uint, string> _methodNames;
    private readonly Dictionary<string, int> _methodCount;
    public TypeDefinition Type => _type;

    public IEnumerable<MethodDefinition> Methods => _type.Methods;

    public TypeContext(GlobalContext global, TypeDefinition type)
    {
        _global = global;
        _type = type;
        _methodNames = new Dictionary<uint, string>();
        _methodCount = new Dictionary<string, int>();
    }

    public Context GetMethodContext(MethodDefinition method)
    {
        return new Context(this, method);
    }

    private string ToLuaMethodName(string name)
    {
        var sb = new StringBuilder();
        for (var i = 0; i < name.Length; i++)
        {
            var ch = name[i];
            if (ch == '.')
                ch = '_';
            sb.Append(ch);
        }

        return sb.ToString();
    }

    public string GetMethodName(MethodDefinition method)
    {
        if (_methodNames.TryGetValue(method.MetadataToken.RID, out var methodName))
        {
            return methodName;
        }

        string name;
        if (method.IsConstructor)
            name = "ctor";
        else
            name = ToLuaMethodName(method.Name);
        if (_methodCount.TryGetValue(name, out var index))
            name += index++;
        else
            index = 1;
        _methodCount[name] = index;
        return name;
    }
}